package com.thiruvathukal.examples.dom.builder;

/*
 * XML code examples by George K. Thiruvathukal. Unless noted otherwise
 * this code is covered by GPLv2. We are still working on the licensing
 * text and will update all code and documentation shortly.
 */

import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

/**
 * @author gkt
 * 
 * This is an example of how to use the DOM interfaces (W3C DOM, that is) to
 * build a DOM document tree.
 */

public class AdHocBuild2 {

	public static void main(String args[]) throws Exception {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(false);
		dbf.setValidating(false);
		DocumentBuilder builder = dbf.newDocumentBuilder();
		Document docBuilder = builder.newDocument();
		Element rootElement = docBuilder.createElement("TaskGroup");
		docBuilder.appendChild(rootElement);
		Element t1, t2, t3, t4, ts1;

		t1 = docBuilder.createElement("Task");
		t1.setAttribute("id", "task1");

		t2 = docBuilder.createElement("Task");
		t2.setAttribute("id", "task2");

		ts1 = docBuilder.createElement("TaskSeries");
		ts1.setAttribute("id", "task4");
		ts1.appendChild(t1);
		ts1.appendChild(t2);

		rootElement.appendChild(ts1);

		t3 = docBuilder.createElement("Task");
		t3.setAttribute("id", "task3");
		rootElement.appendChild(t3);

		t4 = docBuilder.createElement("Task");
		t4.setAttribute("id", "task4");
		rootElement.appendChild(t4);
		OutputFormat format = new OutputFormat(docBuilder, "UTF-8", true);
		StringWriter stringOut = new StringWriter();
		XMLSerializer serial = new XMLSerializer(stringOut, format);
		try {
			serial.asDOMSerializer();
			serial.serialize(docBuilder.getDocumentElement());
		} catch (Exception e) {
			System.err.println("Exception " + e);
		}
		System.out.println("XML\n---");
		System.out.println(stringOut.toString());
	}
}